package org.dyndns.opendemogroup.optimizer;

import java.util.Random;

/**
 * Some array-oriented convenience methods.
 */
public class ArrayUtil
{
	// TODO: Make this into generics
	// TODO: See if it would be faster to invoke System.arraycopy
	public static void copy ( double[] sourceArray, double[] targetArray,
			int startIndex, int endIndex )
	{
		for ( int i = startIndex; i <= endIndex; i++ )
		{
			targetArray[i] = sourceArray[i];
		}
	}

	/**
	 * <p>
	 * Randomly permute the specified array using the specified source of
	 * randomness. All permutations occur with equal likelihood assuming that
	 * the source of randomness is fair.
	 * </p>
	 * <p>
	 * This implementation traverses the array backwards, from the last element
	 * up to the second, repeatedly swapping a randomly selected element into
	 * the "current position". Elements are randomly selected from the portion
	 * of the array that runs from the first element to the current position,
	 * inclusive.
	 * </p>
	 * <p>
	 * This method runs in linear time.
	 * </p>
	 * 
	 * @see java.util.Collections#shuffle(List, Random)
	 * @param sourceArray
	 *        the array to be shuffled.
	 * @param randomSource
	 *        the source of randomness to use to shuffle the array.
	 */
	public static void shuffle ( double[] sourceArray, Random randomSource )
	{
		final int length = sourceArray.length;
		for ( int i = length - 1; i > 0; i-- )
		{
			/*
			 * "Elements are randomly selected from the portion of the list that
			 * runs from the first element to the current position, inclusive."
			 */
			final int randomIndex = randomSource.nextInt ( i + 1 );
			// { swap sourceArray[i] with sourceArray[randomIndex]
			final double temp = sourceArray[i];
			sourceArray[i] = sourceArray[randomIndex];
			sourceArray[randomIndex] = temp;
			// }
		}
	}
}
